package com.aw.baselib.net.callback

import com.aw.baselib.R
import com.aw.baselib.base.AwBaseApplication
import com.aw.baselib.base.AwCustomResponseBean
import com.aw.baselib.bean.rx.EventReLoginType
import com.aw.baselib.util.AwLog.d
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus

/**
 * @author : hzw
 * @date : 2021/12/10
 */
class AwCustomRspSubscriber<T : AwCustomResponseBean?>(private val mRspCallback: AwCustomRspCallback<T>?) :
    Consumer<T?> {
    override fun accept(t: T?) {
        if (null == mRspCallback) {
            d("===AwCustomRspSubscriber callback is null, return")
        } else {
            if (t == null) {
                mRspCallback.onFailure(UNKNOWN_CODE,
                    AwBaseApplication.instance?.getString(R.string.common_server_return_empty_data)
                )
            } else if (t.isTokenError) {
                EventBus.getDefault().postSticky(EventReLoginType(null))
            } else if (t.isSuccess) {
                mRspCallback.onSuccess(t)
            } else {
                mRspCallback.onFailure(t.code, t.msg)
            }
            mRspCallback.onCompleted()
        }
    }

    companion object {
        const val UNKNOWN_CODE = -1
    }
}